package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.clients.schedule.ITaskClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.TaskDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.service.WmAutoScanService;
import com.heima.wemedia.service.WmTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @author xiaquanen
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/7/26 10:21:21
 */
@Service
public class WmTaskServiceImpl implements WmTaskService {

    @Autowired
    private ITaskClient iTaskClient;

    @Autowired
    private WmAutoScanService wmAutoScanService;

    /**
     * 向延迟服务中添加任务
     *
     * @param wmNews
     */
    @Override
    @Async    //异步
    public void addTask(WmNews wmNews) {
        TaskDto taskDto=new TaskDto();
        taskDto.setTaskType(1001);   //任务类型，用于标记当前任务是文章任务
        taskDto.setPriority(1);  //优先级，用于区分文章任务中的不同的细分任务，配合类型一起来作为redis中的key
        taskDto.setExecuteTime(wmNews.getPublishTime().getTime());  //执行时间
        taskDto.setParameters(wmNews.getId().toString());  //真正传递参数的地方
        iTaskClient.addTask(taskDto);
    }

    /**
     * 从redis中的list集合中拉取服务
     *
     */
    @Override
    @Scheduled(cron = "0/1 * * * * ?")
    public void pullTask()
    {
        ResponseResult responseResult = iTaskClient.pullTask(1001, 1);
        if(200==responseResult.getCode())
        {
            String jsonString = responseResult.getData().toString();
            TaskDto taskDto = JSON.parseObject(jsonString, TaskDto.class);
            String wmNewsId = taskDto.getParameters();
            //调用审核服务
            wmAutoScanService.autoScanWmNews(Integer.valueOf(wmNewsId));
        }
    }
}
